<template>
  <div>
    <van-tabbar v-if="showNavBar" v-model="active" active-color="#FA6408">
      <van-tabbar-item icon="wap-home" replace to="/MainView">首页</van-tabbar-item>
      <van-tabbar-item icon="map-marked" replace to="/MapView">发现</van-tabbar-item>
      <van-tabbar-item icon="chat" :badge="badge" replace to="/MessageView">消息</van-tabbar-item>
      <van-tabbar-item icon="cart" @click="handleCartClick">购物车</van-tabbar-item>
      <van-tabbar-item icon="user" replace to="/MyView">我的</van-tabbar-item>
    </van-tabbar>
  </div>
</template>

<script>
import { Tabbar as VanTabbar, TabbarItem as VanTabbarItem,Toast } from 'vant';

export default {
  name: "NavDock",
  components: {
    VanTabbar,
    VanTabbarItem
  },
  data() {
    return {
      // 消息数量
      badge: 6,
      // 默认激活的图标
      active: 0,
      // 是否显示导航栏
      showNavBar: false
    };
  },
  methods: {
    handleCartClick() {
      const storedUser = JSON.parse(sessionStorage.getItem("username"));
      if (storedUser) {
        this.$router.push({ name: 'cart' }).catch(err => {
          if (err.name !== 'NavigationDuplicated' && err.name !== 'NavigationCancelled') {
            throw err;
          }
        });
      } else {
        Toast.fail("请先登录");
        this.$router.push('/').catch(err => {
          if (err.name !== 'NavigationDuplicated' && err.name !== 'NavigationCancelled') {
            throw err;
          }
        });
      }
    }
  },
  watch: {
    // 监听路由变化
    $route(to) {
      this.showNavBar = to.meta.showNavBar;
      this.active = to.meta.active;
    }
  },
  mounted() {
    // 初始化时检查当前路由
    this.showNavBar = this.$route.meta.showNavBar;
    this.active = this.$route.meta.active;
  }
};
</script>
